<template>
  <div>
    <Row>
      <span style="font-weight:bold">系统累计包含:</span>
    </Row>
    <Row :gutter="20" type="flex" justify="center">
      <i-col
        :xs="12"
        :md="8"
        :lg="4"
        v-for="(infor, i) in inforCardData"
        :key="`infor-${i}`"
        style="height: 120px;padding-bottom: 10px;"
      >
        <infor-card shadow :color="infor.color" :icon="infor.icon" :icon-size="36">
          <count-to :end="infor.count" count-class="count-style" />
          <p>{{ infor.title }}</p>
        </infor-card>
        <Spin size="large" fix v-if="loadingCountUp"></Spin>
      </i-col>
      <i-col :xs="12" :md="8" :lg="4">
        <Card shadow style="height: 110px">
        </Card>
      </i-col>
    </Row>
    <Row style="margin-top:10px">
      <Card shadow>
        <span style="display: inline-block; margin-right:10px; font-weight:bold;">选择画像月份:</span>
        <DatePicker type="month" :value="portraitDate" placeholder="选择画像月份" style="width: 400px" @on-change="onDateSelected"></DatePicker>
        <Button type="primary" @click="requestData" style="display: inline-block; margin-left:10px;">获取</Button>
      </Card>
    </Row>
    <Row :gutter="16" style="margin-top:10px">
      <i-col :md="18" :lg="16" :xl="13">
        <Card shadow>
          <v-chart :options="portraitPie" @click="pieClicked" style="height:600px"/>
          <Spin size="large" fix v-if="loadingPie"></Spin>
        </Card>
      </i-col>
      <i-col :md="6" :lg="8" :xl="11">
        <Card shadow style="height:600px">
          <Table border :columns="tableTitle" :data="tableData" :height="550"></Table>
          <Spin size="large" fix v-if="loadingTable"></Spin>
        </Card>
      </i-col>
    </Row>
    <Row :gutter="16" style="margin-top:10px">
      <Card shadow>
        <v-chart :options="departmentsBar" @click="pieClicked" style="height:800px;width:90%"/>
        <Spin size="large" fix v-if="loadingDepartmentsBar"></Spin>
      </Card>
    </Row>
  </div>
</template>

<script>
import InforCard from '_c/info-card'
import CountTo from '_c/count-to'
import { ChartPie, ChartBar } from '_c/charts'
import ECharts from 'vue-echarts'
// import { stringToDate } from '@/libs/util'
import { newDateYearMonthToString } from '@/libs/util'
export default {
  name: 'home',
  components: {
    InforCard,
    CountTo,
    ChartPie,
    ChartBar,
    'v-chart': ECharts
  },
  data () {
    return {
      loadingCountUp: true,
      loadingPie: true,
      loadingDepartmentsBar: true,
      loadingTable: true,
      departmentId: 2,
      childDepartments: '',
      portraitDate: '2019-09',
      portraitData: [],
      inforCardData: [
        {
          title: '优秀类业务',
          icon: 'md-person-add',
          count: 0,
          color: '#91c7ae'
        },
        {
          title: '良好类业务',
          icon: 'md-locate',
          count: 0,
          color: '#61a0a8'
        },
        {
          title: '一般类业务',
          icon: 'md-help-circle',
          count: 0,
          color: '#2f4545'
        },
        {
          title: '关注类业务',
          icon: 'md-share',
          count: 0,
          color: '#d48265'
        },
        {
          title: '重点关注类业务',
          icon: 'md-chatbubbles',
          count: 0,
          color: '#c23531'
        }
      ],
      portraitPie: {
        title: {
          text: '芒市支行机构画像',
          subtext: '9月份',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          show: true,
          orient: 'vertical',
          left: 'right',
          data: ['优秀', '良好', '一般', '关注', '重点关注']
        },
        series: [
          {
            name: '画像数据',
            type: 'pie',
            radius: '65%',
            center: ['50%', '60%'],
            data: [
              { value: 335, name: '优秀' },
              { value: 310, name: '良好' },
              { value: 234, name: '一般' },
              { value: 135, name: '关注' },
              { value: 148, name: '重点关注' }
            ],
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        color: [
          '#91c7ae',
          '#61a0a8',
          '#2f4545',
          '#d48265',
          '#c23531'
        ]
      },
      tableTitle: [
        {
          title: '机构ID',
          key: 'id',
          width: 80
        },
        {
          title: '机构名称',
          key: 'name'
        },
        {
          title: '类型',
          key: 'type',
          width: 120
        },
        {
          title: '数量',
          key: 'count',
          width: 80
        },
        {
          title: '负责人',
          key: 'charger',
          width: 100
        }
      ],
      tableData: [
      ],
      departmentsBar: {
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['优秀', '良好', '一般', '关注', '重点关注']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: []
        },
        series: [
          {
            name: '优秀',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'insideRight'
              }
            },
            data: []
          },
          {
            name: '良好',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'insideRight'
              }
            },
            data: []
          },
          {
            name: '一般',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'insideRight'
              }
            },
            data: []
          },
          {
            name: '关注',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'insideRight'
              }
            },
            data: []
          },
          {
            name: '重点关注',
            type: 'bar',
            stack: '总量',
            label: {
              normal: {
                show: true,
                position: 'insideRight'
              }
            },
            data: []
          }
        ],
        color: [
          '#91c7ae',
          '#61a0a8',
          '#2f4545',
          '#d48265',
          '#c23531'
        ]
      }
    }
  },
  mounted () {
    this.portraitDate = this.initPortraitDatePicker()
    // 获取数据项统计
    this.axios.get('/api/v1/portrait/record-statistics', { params: {
      department_id: this.departmentId
    } }).then((response) => {
      var data = response.data
      for (var i = 0; i < 5; i++) {
        var dataItem = data[i]
        this.inforCardData[i].count = dataItem[0].count
      }
      this.loadingCountUp = false
    })
    this.showSpinLoading()
    // 获取部门数据
    this.axios.get('/api/v1/portrait/departments', { params: {
      parent_id: this.departmentId
    } }).then((response) => {
      var data = response.data.data
      this.childDepartments = []
      data.forEach(element => {
        this.childDepartments[element.id] = element
      })
      this.portraitDate = newDateYearMonthToString()
      // 加载机构画像数据
      this.loadPortrait(this.portraitDate, this.departmentId)
      this.stopSpinLoading()
    })
  },
  methods: {
    requestData () {
      if (this.portraitDate === '') {
        this.$Message.error({
          content: '数据日期未选择!',
          duration: 3
        })
        return
      }
      this.loadPortrait(this.portraitDate, this.departmentId)
    },
    onDateSelected (date) {
      this.portraitDate = date
    },
    pieClicked (event) {
      var type = event.data.name
      this.updateDateTable(type)
    },
    getNowDateString () {
      var date = new Date()
      var year = 2019
      var month = date.getMonth()
      if (month === 0) {
        year = year - 1
        month = 12
      } else {
        month = month - 1
      }
      return year + '-' + month
    },
    loadPortrait (dateStr, departmentId) {
      this.loadingPie = true
      // 获取饼图数据
      this.axios.get('/api/v1/portrait/overall', { params: {
        department_id: departmentId,
        date: dateStr
      } }).then((response) => {
        var data = response.data.data
        this.loadingPie = false
        this.portraitData = this.decoratePieData(data)
        // 更新饼图信息
        this.updatePieChart()
        this.updateDepartmentsBar()
        this.updateDateTable('优秀')
      })
    },
    decoratePieData (data) {
      var decoratedDate = []
      var dateStr = this.portraitDate
      this.childDepartments.forEach(department => {
        decoratedDate[department.id] = []
        decoratedDate[department.id][dateStr] = []
        decoratedDate[department.id][dateStr]['优秀'] = []
        decoratedDate[department.id][dateStr]['良好'] = []
        decoratedDate[department.id][dateStr]['一般'] = []
        decoratedDate[department.id][dateStr]['关注'] = []
        decoratedDate[department.id][dateStr]['重点关注'] = []
      })
      // 获取日期字符串
      var targetString = this.computedDateString(dateStr)
      // 处理周期为月的数据
      data.forEach(element => {
        var dateString = element.record_date.substring(0, 7)
        switch (element.data_cycle) {
          case '月':
            if (dateString === targetString['month']) {
              decoratedDate[element.department_id][dateStr][element.evaluation_result].push(element)
            }
            break
          case '季度':
            if (dateString === targetString['quarter']) {
              decoratedDate[element.department_id][dateStr][element.evaluation_result].push(element)
            }
            break
          case '半年':
            if (dateString === targetString['half_year']) {
              decoratedDate[element.department_id][dateStr][element.evaluation_result].push(element)
            }
            break
          case '年':
            if (dateString === targetString['year']) {
              decoratedDate[element.department_id][dateStr][element.evaluation_result].push(element)
            }
            break
        }
      })
      return decoratedDate
    },
    computedDateString (dateStr) {
      var year = parseInt(dateStr.substring(0, 4))
      var month = parseInt(dateStr.substring(5, 7))
      var dateString = []
      // 月
      dateString['month'] = dateStr
      // 季度
      var quarter = Math.floor(month / 3)
      if (quarter === 0) {
        var tYear = year - 1
        dateString['quarter'] = tYear + '12'
      } else {
        var finalMonth = quarter * 3
        if (finalMonth < 10) {
          finalMonth = '0' + finalMonth
        }
        dateString['quarter'] = year + '-' + finalMonth
      }
      // 半年
      if (month === 12) {
        dateString['half_year'] = year + '-12'
      } else if (month >= 6) {
        dateString['half_year'] = year + '-06'
      } else {
        var targetYear = year - 1
        dateString['half_year'] = targetYear + '-12'
      }
      // 年
      if (month === 12) {
        dateString['year'] = year + '-12'
      } else {
        dateString['year'] = (year - 1) + '-12'
      }
      return dateString
    },
    showSpinLoading () {
      this.$Spin.show({
        render: (h) => {
          return h('div', [
            h('Icon', {
              'class': 'demo-spin-icon-load',
              props: {
                type: 'ios-loading',
                size: 18
              }
            }),
            h('div', 'Loading')
          ])
        }
      })
    },
    stopSpinLoading () {
      this.$Spin.hide()
    },
    updatePieChart () {
      var year = this.portraitDate.substring(0, 4)
      var month = this.portraitDate.substring(5, 7)
      var pieTitle = year + '年' + month + '月'
      this.portraitPie.title.subtext = pieTitle
      // 统计项数
      var statistics = []
      statistics['优秀'] = 0
      statistics['良好'] = 0
      statistics['一般'] = 0
      statistics['关注'] = 0
      statistics['重点关注'] = 0
      this.childDepartments.forEach(element => {
        var dataItems = this.portraitData[element.id][this.portraitDate]
        statistics['优秀'] = statistics['优秀'] + this.getRecordsNumberByType('优秀', dataItems)
        statistics['良好'] = statistics['良好'] + this.getRecordsNumberByType('良好', dataItems)
        statistics['一般'] = statistics['一般'] + this.getRecordsNumberByType('一般', dataItems)
        statistics['关注'] = statistics['关注'] + this.getRecordsNumberByType('关注', dataItems)
        statistics['重点关注'] = statistics['重点关注'] + this.getRecordsNumberByType('重点关注', dataItems)
      })
      // 更新西瓜图
      this.portraitPie.series[0].data.forEach(element => {
        element.value = statistics[element.name]
      })
    },
    updateDateTable (type) {
      this.loadingTable = true
      // 更新Table中的数据
      this.tableData = []
      this.portraitData.forEach((department, departmentId) => {
        if (department[this.portraitDate][type].length > 0) {
          var departmentData = {
            id: departmentId,
            name: this.childDepartments[departmentId].name,
            type: type,
            count: department[this.portraitDate][type].length,
            charger: this.childDepartments[departmentId].charger
          }
          this.tableData.push(departmentData)
        }
      })
      this.loadingTable = false
    },
    updateDepartmentsBar () {
      this.loadingDepartmentsBar = true
      this.departmentsBar.yAxis.data = []
      // 清空存在的数据
      this.departmentsBar.legend.data.forEach((data, index) => {
        this.departmentsBar.series[index].data = []
      })
      this.childDepartments.forEach(department => {
        // 更新纵坐标中机构名称
        this.departmentsBar.yAxis.data.push(department.name)
      })
      this.childDepartments.forEach(department => {
        this.departmentsBar.legend.data.forEach((type, index) => {
          this.departmentsBar.series[index].data.push(this.portraitData[department.id][this.portraitDate][type].length)
        })
      })
      this.loadingDepartmentsBar = false
    },
    getRecordsNumberByType (type, dataItems) {
      return dataItems[type].length
    },
    initPortraitDatePicker () {
      var currentDate = new Date()
      var dateStr = ''
      if (currentDate.getMonth() <= 1) {
        dateStr = (currentDate.getFullYear() - 1) + '-12'
      } else {
        if (currentDate.getMonth() < 10) {
          dateStr = currentDate.getFullYear() + '-0' + currentDate.getMonth()
        } else {
          dateStr = currentDate.getFullYear() + '-' + currentDate.getMonth()
        }
      }
      return dateStr
    }
  }
}
</script>

<style lang="less">
  .count-style {
    font-size: 50px;
  }
</style>
